package com.qbm.association.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qbm.association.bean.ResultBean;
import com.qbm.association.bean.UserTypeEnum;
import com.qbm.association.config.Audience;
import com.qbm.association.entity.Student;
import com.qbm.association.mapper.StudentMapper;
import com.qbm.association.service.PasswordService;
import com.qbm.association.service.StudentService;
import com.qbm.association.util.JWTTokenUtil;
import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Aron
 * @since 2022-02-07
 */
@RestController
@RequestMapping("/association/student")
public class StudentController {
    @Resource
    private StudentService studentService;

    @Autowired
    private Audience audience;

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private PasswordService passwordService;

    @GetMapping("getStudentUserName")
    public ResultBean getUserName(HttpServletRequest request) {
        String name = studentService.getByUsername(JWTTokenUtil.getUserName
                (request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY), audience.getBase64Secret())).getName();
        return ResultBean.success(name,"获取成功");
    }
    @GetMapping("getStudentUserNameById")
    public ResultBean getStudentUserNameById(Integer id) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        Student student = studentMapper.selectOne(queryWrapper);
        return ResultBean.success(student,"获取成功");
    }

    @GetMapping("getStudent")
    public ResultBean getStudent(HttpServletRequest request) {
        Student byUsername = studentService.getByUsername(JWTTokenUtil.getUserName
                (request.getHeader(JWTTokenUtil.AUTH_HEAD_KEY), audience.getBase64Secret()));
        return ResultBean.success(byUsername,"获取成功");
    }

    @GetMapping("getPageStudentList")
    public ResultBean getPageClubByStatus(Integer currentPage, String name) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        if (name != null && name.length() != 0) {
            queryWrapper.like("name", name);
        }
        Page<Student> page = new Page<>(currentPage, 5);
        Page<Student> page1 = studentMapper.selectPage(page, queryWrapper);
        return ResultBean.success(page1, "获取成功");
    }


    @PostMapping("addStudent")
    public ResultBean addStudent(Student student) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", student.getStudentId());
        boolean isTrue = studentService.list(queryWrapper).size() == 0;
        Assert.isTrue(isTrue,"该学生已存在");
        studentService.register(student,student.getStudentId().toString());
        return ResultBean.success( "添加成功");
    }

    @PostMapping("updateStudent")
    public ResultBean updateStudent(Student student) {
        boolean isTrue = studentService.updateById(student);
        Assert.isTrue(isTrue,"编辑失败");
        return ResultBean.success( "编辑成功");
    }

    @PostMapping("deleteStudent")
    public ResultBean deleteStudent(Student student) {
        boolean isTrue = studentService.removeById(student);
        Assert.isTrue(isTrue,"删除失败");
        return ResultBean.success( "删除成功");
    }

    @PostMapping("updateStudentAndPassword")
    public ResultBean updateStudentAndPassword(Student student,String oldPassword, String password) {
        boolean isTrue = passwordService.matchPassword(student.getId(), UserTypeEnum.STUDENT, oldPassword);
        Assert.isTrue(isTrue,"旧密码不正确");
        isTrue = passwordService.updateUserPassword(student.getId(),UserTypeEnum.STUDENT,password);
        Assert.isTrue(isTrue,"修改失败");
        return ResultBean.success( "修改成功");
    }

    /**
     * 上传头像图片
     *
     * @param file 要上传的图片文件
     * @return
     */
    @PostMapping("uploadStudentExcel")
    public ResultBean uploadStudentExcel(MultipartFile file) {
        try {
            if (!file.isEmpty()) {
                studentService.excelImport(file);
                // TODO: 此处可以根据项目需求的业务进行操作，例如此处操作的是头像，可以将头像url保存到数据库，用户登录后，获取相应的url获取头像图片。
                return ResultBean.success("文件上传成功");
            } else {
                return ResultBean.fail("文件上传失败1");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBean.fail("文件上传失败2");
        }
    }
    //    文件下载功能
    @RequestMapping("excel/download")
    public  void downExcel(HttpServletResponse res){
        try {
            //获取要下载的模板名称
            String fileName = "student.xlsx";
            //设置要下载的文件的名称
            res.setHeader("Content-disposition", "attachment;fileName=" + fileName);
            //通知客服文件的MIME类型
            res.setContentType("application/vnd.ms-excel;charset=UTF-8");
            //获取文件的路径
            //String filePath = getClass().getResource("/template/" + fileName).getPath();
            //excel模板路径
            File cfgFile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static/excel/student.xlsx");
            FileInputStream input = new FileInputStream(cfgFile);
            //            FileInputStream input = new FileInputStream(new File("d://"+fileName));
            OutputStream out = res.getOutputStream();
            byte[] b = new byte[2048];
            int len;
            while ((len = input.read(b)) != -1) {
                out.write(b, 0, len);
            }
            //修正 Excel在“xxx.xlsx”中发现不可读取的内容。是否恢复此工作薄的内容？如果信任此工作簿的来源，请点击"是"
            res.setHeader("Content-Length", String.valueOf(input.getChannel().size()));
            input.close();
            System.out.println("应用导入模板下载完成");
        } catch (Exception ex) {
            System.out.println("应用导入模板下载失败！");
        }
    }
    @GetMapping("download")
    public void getUrlFile( HttpServletResponse response) {
//        System.err.println(url);
        /**
         * 写文件
         */
        String fileName = "D://test//simpleWrite" + System.currentTimeMillis() + ".xlsx";
        File file = new File(fileName);
        studentService.writeExcel(fileName);

        if (!(file.exists() && file.canRead())) {
            System.out.println("文件不存在");
        }
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            inputStream.read(data, 0, data.length);
            inputStream.close();
            response.setContentType("image/png;charset=utf-8");
            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
            stream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

